<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js"></script>
</head>

<body>
    <input type="text" name="" id="title">
    <ul>
        <!-- <li>
            <input type="text" name="" id="">
            <p></p>
            <button>删除</button>
        </li> -->
    </ul>
    <script src="./request.js"></script>
    <script>


        /*
            1-列表
            2-发布
            3-删除
            4-修改

        */
        /* 
             4-修改
        
        */
        let todosAPI = "/todos";

        async function changeState(id, completed) {
            completed = completed == 1 ? 0 : 1
            await http.patch(todosAPI + '/' + id, { completed })
            loadList()

        }
        /* 

                3-删除

        */
        async function delFn(id) {
            console.log(id);
            // 删除 传入动态id
            await http.delete(todosAPI + '/' + id)
            loadList()
        }
        /* 
             2-发布
        
        
        */
        document.onkeydown = async e => {
            if (e.keyCode == 13) {
                let ipt = document.querySelector("#title")
                let title = ipt.value;
                await http.post(todosAPI, { title });
                loadList()
                ipt.value = ''
            }
        }

        // 1-列表
        async function loadList() {
            let r = await http.get(todosAPI);
            console.log(r.data);
            let liStr = r.data.data.map(v => `
                <li>
                    <input onchange="changeState('${v._id}',${v.completed})" type="checkbox" name="" id="" ${v.completed ? 'checked' : ''}>
                <p> ${v.title}</p>
                    <button onclick="delFn('${v._id}')">删除</button>
                </li >
            `).join('')
            document.querySelector("ul").innerHTML = liStr
        }


        loadList()




    </script>

</body>

</html>